<?php

namespace app\libs\html;

class Colorizer
{

    public static function php($str)
    {
        // string
        $str = preg_replace("/(\".+\")/", "<span class='string'>$1</span>", $str);

        // keywords
        $keywords = [
            'namespace ', 'use ', 'trait ', 'class ', 'interface ', 'abstract ', 'extends ', 'implements ',
            'public ', 'protected ', 'private ', 'final ', 'static ', 'const ', 'function ', 'self ', 'new ',
            'while', 'for', 'do', 'foreach', 'endforeach', 'if', 'elseif', 'else', 'endif', 'switch', 'case', 'break', 'continue', 'return', ' as '
        ];
        foreach($keywords as $keyword)
            $str = self::wrap($str, $keyword, 'keyword');

        // conditions
        $conditions = [
            ' && ', ' || ', ' == ', '!', ' and ', ' or ', ' xor ', ' instanceof '
        ];
        foreach($conditions as $condition)
            $str = self::wrap($str, $condition, 'condition');

        // natives
        $natives = [
            'null', 'true', 'false'
        ];
        foreach($natives as $native)
            $str = self::wrap($str, $native, 'native');

        // vars
        $str = preg_replace("/(\\$[a-zA-Z0-9]+)/", "<span class='variable'>$1</span>", $str);

        // comment
        $str = preg_replace("/(\\/\\/[\s\w]*)/", "<span class='comment'>$1</span>", $str);
        $str = preg_replace("/(\\/\\*[\s\S]+\\*\\/)/", "<span class='comment'>$1</span>", $str);

        // int
        $str = preg_replace("/([0-9]+)/", "<span class='int'>$1</span>", $str);

        // const
        $str = preg_replace("/([\W])([A-Z_]+)([\W])/", "$1<span class='const'>$2</span>$3", $str);

        // path
        //$str = preg_replace("/(\\\?[a-z0-9]+\\\[a-z0-9]+)/", "<span class='path'>$1</span>", $str);

        return $str;
    }

    protected static function wrap($haystack, $needle, $tag)
    {
        //return preg_replace("/($needle)/", "<span class='$tag'>$1</span>", $haystack);
        return str_replace($needle, '<span class="'.$tag.'">'.$needle.'</span>', $haystack);
    }

}
